import React, { useEffect, useRef, useState } from 'react';
// 数据没照片的时候的默认照片
import defaultImg from 'assets/error.png';
import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  DatePicker,
  Table,
  Tag,
  Space,
  message,
} from 'antd';
import { Link } from 'react-router-dom';
// 引入图标
import {
  EditOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons';
// 引入接口
import { getArticlesApi, delArticleByIdAPI } from 'api/channel';
import confirm from 'antd/lib/modal/confirm';
import Channel from 'components/Channel';
const { RangePicker } = DatePicker;
export default function ArticleList(props) {
  const formDataRef = useRef();
  // 创建Ref保存分页信息
  const pageInfoRef = useRef({});

  // 状态的修改
  const articleStatus = [
    { id: -1, name: '全部', color: 'magenta' },
    { id: 0, name: '草稿', color: 'orange' },
    { id: 1, name: '待审核', color: 'red' },
    { id: 2, name: '审核通过', color: 'green' },
    { id: 3, name: '审核失败', color: 'cyan' },
  ];

  // 获取文章列表
  const [articlesData, setArticlesData] = useState({});
  const getArticlesList = async (params) => {
    const res = await getArticlesApi(params);
    setArticlesData(res.data);
  };

  useEffect(() => {
    // // 获取文章列表
    getArticlesList();
  }, []);

  // 文章列表分页的事件
  const changePage = async (page, per_page) => {
    // 3. 分页查询时带上formData，💥注意筛选表单为空时做判断
    pageInfoRef.current = { page, per_page };
    const res = await getArticlesApi({ page, per_page });
    setArticlesData(res.data);
  };

  // 能够触发筛选
  const onFinish = async (values) => {
    let formData = {
      ...values,
    };

    if (formData.status === -1) {
      delete formData.status;
    }

    if (formData.date) {
      const begin_pubdate = formData.date[0]
        .startOf('day')
        .format('YYYY-MM-DD HH:mm:ss');
      const end_pubdate = formData.date[1]
        .endOf('day')
        .format('YYYY-MM-DD HH:mm:ss');
      formData.begin_pubdate = begin_pubdate;
      formData.end_pubdate = end_pubdate;
      delete formData.date;
    }

    // 2. 提交筛选时，存储表单数据
    formDataRef.current = formData;
    getArticlesList(formData);
  };

  // 删除数据
  const handleDelete = (id) => {
    // console.log(id);
    confirm({
      title: '温馨提示？',
      icon: <ExclamationCircleOutlined />,
      content: '你确定要删除文章吗',
      onOk: async () => {
        // 发送请求进行删除
        await delArticleByIdAPI(id);
        message.success('删除成功', 1);
        const formData = formDataRef.current || {};
        // 注意带上分页的数据上去
        getArticlesList({ ...formData, ...pageInfoRef.current });
      },
    });
  };

  const columns = [
    {
      title: '封面',
      render(item) {
        // 情况1：无图，渲染默认图片
        // 情况2：有图，渲染第一张图片
        return (
          <img
            src={item.cover.type === 0 ? defaultImg : item.cover.images[0]}
            title={item.title}
            alt={item.title}
            style={{ width: 100, height: 60, objectFit: 'cover' }}
          />
        );
      },
    },
    {
      title: '标题',
      dataIndex: 'title',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (status) => {
        const tagInfo = articleStatus.find((item) => item.id === status);
        return <Tag color={tagInfo.color}>{tagInfo.name}</Tag>;
      },
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
    },
    {
      title: '操作',
      // render 生成复杂数据的渲染函数，参数分别为当前行的值，当前行数据，行索引
      render: (value, record) => {
        return (
          <Space>
            <Button
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
              // 跳转路由   传参id
              onClick={() => props.history.push(`/edit/${record.id}`)}
            ></Button>
            <Button
              type="primary"
              shape="circle"
              danger
              icon={<DeleteOutlined />}
              onClick={() => handleDelete(record.id)}
            ></Button>
          </Space>
        );
      },
    },
  ];

  // const Option = Select;
  return (
    <div style={{ height: 'calc(100vh - 110px)', overflow: 'auto' }}>
      {/* 卡片 */}
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>文章列表</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        {/* 单选框 */}
        {/* onFinish  触发提交事件 */}
        <Form
          onFinish={onFinish}
          autoComplete="off"
          initialValues={{ status: -1 }}
        >
          <Form.Item label="状态" name="status">
            <Radio.Group>
              <Radio value={-1}>全部</Radio>
              <Radio value={0}>草稿</Radio>
              <Radio value={1}>待审核</Radio>
              <Radio value={2}>审核通过</Radio>
              <Radio value={3}>审核失败</Radio>
            </Radio.Group>
          </Form.Item>

          {/* 选择器  -- 下拉框 */}
          <Form.Item label="频道" name="channel_id">
            <Channel></Channel>
          </Form.Item>

          {/* 选中日期 -- 日历 */}
          <Form.Item label="日期" name="date">
            <RangePicker />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit">
              筛选
            </Button>
          </Form.Item>
        </Form>
        <Card title={`根据筛选条件共查询到${articlesData.total_count}条数据`}>
          <Table
            dataSource={articlesData.results}
            columns={columns}
            rowKey="id"
            pagination={{
              position: ['bottomCenter'],
              current: articlesData.page,
              pageSize: articlesData.per_page,
              total: articlesData.total_count,
              // 分页功能，页码改变时触发的事件、
              onChange: changePage,
            }}
          />
        </Card>
      </Card>
    </div>
  );
}
